#version 330 core
out vec4 FragColor;

uniform sampler2D gPosition;    // 世界空间位置纹理采样器
uniform sampler2D gNormal;      // 法线向量纹理采样器
uniform sampler2D gAlbedoSpec;  // 漫反射颜色 + 高光强度纹理采样器

uniform float Linear;
uniform float Quadratic;

in vec3 vInstanceColor;
in vec3 vInstancePos;

uniform vec3 viewPos;// 观察者位置

void main()
{          
    vec2 texCoord = gl_FragCoord.xy / textureSize(gPosition, 0);

    // 从G缓冲中获取数据
    vec3 FragPos = texture(gPosition, texCoord).rgb;  // 提取世界坐标
    vec3 Normal = texture(gNormal, texCoord).rgb;      // 提取法线向量
    vec3 Diffuse = texture(gAlbedoSpec, texCoord).rgb;  // 提取漫反射颜色
    float Specular = texture(gAlbedoSpec, texCoord).a; // 提取高光强度
    
    float distance = length(vInstancePos - FragPos);

    // 按常规方式计算光照
    vec3 lighting = vec3(0.f);
    vec3 viewDir = normalize(viewPos - FragPos);  // 计算观察方向
    // diffuse
    vec3 lightDir = normalize(vInstancePos - FragPos);
    vec3 diffuse = max(dot(Normal, lightDir), 0.0) * Diffuse * vInstanceColor;
    // specular
    vec3 halfwayDir = normalize(lightDir + viewDir);  
    float spec = pow(max(dot(Normal, halfwayDir), 0.0), 16.0);
    vec3 specular = vInstanceColor * spec * Specular;
    // attenuation
    
    float attenuation = 1.0 / (1.0 + Linear * distance + Quadratic * distance * distance);

    diffuse *= attenuation;
    specular *= attenuation;
    lighting += diffuse + specular;        
    
    FragColor = vec4(lighting, 1.0);  // 输出最终光照颜色
}  